package com.cn.web;

import com.alibaba.fastjson.JSONObject;
import com.cn.entity.CustomerSimpleInfo;
import com.cn.entity.Finally;
import com.cn.service.CustomerSimpleInfoService;
import com.cn.service.FinallyService;
import com.cn.utils.StringUtil;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenyuncong on 2019/5/9.
 */
@RequestMapping("es")
@RestController
public class ESWeb {

    @Autowired
    private TransportClient client;

    @Autowired
    private FinallyService finallyService;
    @Autowired
    private CustomerSimpleInfoService customerSimpleInfoService;

    @GetMapping("groupData")
    public String groupData() throws Exception {

        int total = customerSimpleInfoService.cuCount();
        int num = total/1000;
        if(total%1000!=0){
            num+=1;
        }
        List<CustomerSimpleInfo> list =null;
        for(int i=0;i<num;i++){
            list = customerSimpleInfoService.getCustomerSimpleInfolimitList(1000,i);
            list.forEach(x->{x.setId(null);});
            customerSimpleInfoService.saveBatch(list);
            System.out.println(i+"--"+list.size());
        }
        return "";
    }

    @GetMapping("testTada")
    public String testTada(){
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        boolQueryBuilder.must(QueryBuilders.matchQuery("house_quantity", "拥有房产"));
        SearchResponse response = client.prepareSearch("tmp-alg-customer")//对应索引
                .setTypes("content")//对应索引type
                .setScroll(TimeValue.timeValueMinutes(10))
                .setSize(100)
                .execute()
                .actionGet();
        while (response.getHits().getHits().length > 0) {
            String scrollId = response.getScrollId();
            System.out.println("scrollId:"+scrollId);
            response = client.prepareSearchScroll(scrollId)
                    .setScroll(TimeValue.timeValueMinutes(10))//设置查询context的存活时间
                    .execute()
                    .actionGet();

            SearchHits hits = response.getHits();
            for (SearchHit hit : hits.getHits()) {
                String hitString = hit.getSourceAsString();
                System.out.println(hitString);
            }

        }
        return "";
    }

    @GetMapping("reloadData")
    public String reloadData() {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("house_quantity", "拥有房产"));

//        RangeQueryBuilder publishDateBuilder = QueryBuilders.rangeQuery("created_at");
//        publishDateBuilder.from("2018-04-22 00:00:00");//格式需要同你创建索引时的格式匹配
//        boolQueryBuilder.filter(publishDateBuilder);

        SearchResponse response = client.prepareSearch("alg-customer-finally")//对应索引
                .setTypes("content")//对应索引type
//                .setFetchSource(new String[]{"customerPhone"}, null)
                .setQuery(boolQueryBuilder)
                .setScroll(TimeValue.timeValueMinutes(10))
                .setSize(100)
                .execute()
                .actionGet();
        List<Finally> list =new ArrayList<>();
        int i = 0;
        while (response.getHits().getHits().length > 0) {
            String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId)
                    .setScroll(TimeValue.timeValueMinutes(10))//设置查询context的存活时间
                    .execute()
                    .actionGet();

            SearchHits hits = response.getHits();
            for (SearchHit hit : hits.getHits()) {
                String hitString = hit.getSourceAsString();
                JSONObject obj = JSONObject.parseObject(hitString);
                try {
                    if(obj.get("phone_no")!=null){
                        if(StringUtil.isPhon2(obj.get("phone_no").toString())){
                            list.add(get(obj.getInnerMap()));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                System.out.println(hitString);//此处可进行业务逻辑
                i++;
            }

            try {
                finallyService.saveBatch(list);
                System.out.println(i+"--"+list.size());
                list.clear();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(i);
        return "ok";
    }

    @GetMapping("get")
    public Map<String, Object> get() {
        GetResponse getResponse = client.prepareGet("alg-customer-finally", "content", "13826196888").get();
        return getResponse.getSource();
    }

    @GetMapping("getCustomerName")
    public String getCustomerName(){
        Map<String,CustomerSimpleInfo> map =new HashMap<>();
        SearchResponse response = client.prepareSearch("hfcrm_pro_customer_new")//对应索引
                .setTypes("data")//对应索引type
                .setFetchSource(new String[] { "customerPhone","customerName"}, null)
//                .setQuery(boolQueryBuilder)
                .setScroll(TimeValue.timeValueMinutes(10))
                .setSize(100)
                .execute()
                .actionGet();
        List<CustomerSimpleInfo> list =new ArrayList<>();

        int ii=0;
        while (response.getHits().getHits().length > 0) {
            String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId)
                    .setScroll(TimeValue.timeValueMinutes(10))//设置查询context的存活时间
                    .execute()
                    .actionGet();

            SearchHits hits = response.getHits();
            CustomerSimpleInfo csi = null;
            for (SearchHit hit : hits.getHits()) {
                String hitString = hit.getSourceAsString();
//                System.out.println(hitString);//此处可进行业务逻辑
                JSONObject obj = JSONObject.parseObject(hitString);
                if(!StringUtils.isEmpty(obj.get("customerPhone")) ){
                    if(StringUtil.isPhon2(obj.get("customerPhone").toString())){
//                        list.add(new CustomerSimpleInfo(obj.get("customerName")==null?null:obj.get("customerName").toString(),obj.get("customerPhone").toString()));
                        if(map.containsKey(obj.get("customerPhone").toString())){
                            csi=map.get(obj.get("customerPhone").toString());
                            if (StringUtil.isZhongWen(obj.get("customerName")==null?null:obj.get("customerName").toString())){
                                csi.setCustomerName(obj.get("customerName").toString());
                            }
                        }else {
                            map.put(obj.get("customerPhone").toString(),new CustomerSimpleInfo(obj.get("customerName")==null?null:obj.get("customerName").toString(),obj.get("customerPhone").toString()));
                        }
                    }
                }

            }
            if(ii==100){
//                break;
            }
            System.out.println("key-size:"+map.keySet().size());
            ii++;
        }

        try {
            map.forEach((k,v)->{
                list.add(v);
            });
            int num=list.size();
            if(num%1000!=0){
                num++;
            }
            int i=0;
            List<CustomerSimpleInfo> clist=new ArrayList<>();
            for (CustomerSimpleInfo c: list){
                clist.add(c);
                if(i%1000==0){
                    customerSimpleInfoService.saveBatch(clist);
                    System.out.println(i+"-"+clist.size());
                    clist.clear();
                }
                i++;
            }
            customerSimpleInfoService.saveBatch(clist);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("reData")
    public void reData() {

        String path = "C:\\file2\\alg-customer-finally.json";
        File file = new File(path);
        BufferedReader br = null;
        if (file.exists()) {
            try {
                br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
                String s = null;
                JSONObject boj = null;
                Map<String, Object> o = null;
                List<Finally> list = new ArrayList<>();
                Finally f = null;
                int i = 0;
                while ((s = br.readLine()) != null) {  //使用readLine方法，一次读一行
                    boj = JSONObject.parseObject(s);
                    o = (Map<String, Object>) boj.get("_source");
                    if (o.containsKey("house_quantity")) {
                        list.add(get(o));
                        i++;
                        if (i % 1000 == 0) {
                            finallyService.saveBatch(list);
                            System.out.println(i + " " + list.size());
                            list.clear();
                        }
                    }
                }
                finallyService.saveBatch(list);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }

                } catch (IOException e1) {
                }
            }
        }

    }

    public Finally get(Map<String, Object> obj) throws Exception {
        Finally f = new Finally();
        Value v = null;
        for (Field field : f.getClass().getDeclaredFields()) {
//            v = field.getAnnotation(Value.class);
            if (obj.containsKey(field.getName())) {
                if (!field.getName().equals("relevance_phone_no")) {
                    field.setAccessible(true);
                    try {
                        if(field.getName().equals("property_places")){
                            int s=obj.get(field.getName())==null ? 0 : obj.get(field.getName()).toString().length();
                            if(s>=400){
                                field.set(f, obj.get(field.getName()).toString().substring(0,400));
                            }else{
                                field.set(f, obj.get(field.getName()));
                            }
                        }else{
                            field.set(f, obj.get(field.getName()));
                        }

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return f;
    }

}
